package com.market.domain.transients;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;

import com.market.domain.Role;
import com.market.domain.User;

/**
 * Create a new UserAuthentication after user login, and set this userAuthentication to
 * SecurityConctextHoder,
 * This class is used by spring security.
 * @author Tong
 *
 */
public class UserAuthentication implements Authentication {

	/**
	 * 
	 */
	private static final long serialVersionUID = 868609774775512063L;

	private User user;

	public UserAuthentication(User user) {
		this.user = user;
	}

	public String getName() {
		return this.user.getFirstName() + "," + this.user.getLastName();
	}

	public Collection<GrantedAuthority> getAuthorities() {

		Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
		for (Role role : this.user.getRoles()) {
			GrantedAuthority ga = new GrantedAuthorityImpl(role.getName());
			authorities.add(ga);
		}
		return authorities;
	}

	public Object getCredentials() {
		return this.user.getId();
	}

	public Object getDetails() {
		// TODO Auto-generated method stub
		return null;
	}

	public Object getPrincipal() {
		return this.user;
	}

	public boolean isAuthenticated() {
		return this.user.getIsLogin();
	}

	public void setAuthenticated(boolean isAuthenticated)
			throws IllegalArgumentException {
		this.user.setIsLogin(isAuthenticated);

	}

}
